package com.dy.lock.screen.api.servlet;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.dy.lock.screen.api.constants.Constant;
import com.dy.lock.screen.api.scoket.Head;
import com.dy.lock.screen.api.scoket.SocketDTO;
import com.dy.lock.screen.api.scoket.TransmissionCode;
import com.dy.lock.screen.api.utils.CommonUtil;
import com.dy.lock.screen.api.utils.IpUtil;
import com.dy.lock.screen.api.utils.MD5Util;
import com.dy.lock.screen.api.utils.ServletUtil;
import com.dy.lock.screen.api.vo.ResultVo;
import com.google.gson.Gson;

/**
 * 
 * @description 测试用
 * @author
 * @date 2012-12-13
 */
public class TestServlet extends SuperServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static Logger log = Logger.getLogger(TestServlet.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setAttribute("org.eclipse.jetty.server.Request.queryEncoding",
				"UTF-8");
		resp.setContentType("text/html;charset=UTF-8");
		resp.setStatus(HttpServletResponse.SC_OK);

		// 获取参数流
		// ServletInputStream stream = req.getInputStream();
		// BufferedReader br = new BufferedReader(new
		// InputStreamReader(stream));
		// String line = null;
		// StringBuilder sb = new StringBuilder();
		// while ((line = br.readLine()) != null) {
		// sb.append(line);
		// }
		// String result = sb.toString().trim();
		String clientIp = IpUtil.getIpAddr(req);
		log.info("============客户端真实Ip：" + clientIp);

		// 获取字符串形式参数
		// 参数1
		String id = req.getParameter("xxxxxxxx");
		// 参数3
		String sign = req.getParameter("sign");

		log.info("xxxxxxxx：" + id + ",sign：" + sign);
		Gson gson = CommonUtil.gson();

		boolean flag = this.validateData(id, sign, resp, req);
		if (flag) {// 数据校验成功
			try {
				SocketDTO dto = sendMessage(id, req);
				Head head = dto.getHead();
				String resCode = head.getResponseCode();
				// String resMsg = head.getResponseMessage();
				String body = dto.getBody();
				if (TransmissionCode.SUCCESS.getCode().equals(resCode)
						&& StringUtils.isNotEmpty(body)) {
					// 把service中返回的信息转成对应的json格式字符串，返回给接口调用者
					ResultVo ri = new ResultVo();
					boolean result = gson.fromJson(body, Boolean.class);
					if (result) {
						ri.setCode(Constant.SUCCESS);
						ri.setStatus(Constant.TRUE);
						ServletUtil.writeResJsonStr(resp, gson.toJson(ri));
					} else {
						ServletUtil.writeErrorStr(resp);
					}
				}

			} catch (Exception e) {
				log.error("异常信息", e);
				// 异常情况，也把对应异常信息的json格式字符串返回给接口调用者
			}

		}

	}

	/**
	 * 向service服务发送请求
	 * 
	 * @param t
	 * @param req
	 * @return
	 */
	private SocketDTO sendMessage(String body, HttpServletRequest req) {
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode(Constant.TEST_ID);
		head.setIp(IpUtil.getIpAddr(req));
		head.setUserId("api");
		return super.send(head, body);
	}

	/**
	 * 数据校验合法性
	 * 
	 * @param id
	 * @param name
	 * @param sign
	 * @param resp
	 * @param req
	 * @return
	 * @throws IOException
	 */
	private boolean validateData(String id, String sign,
			HttpServletResponse resp, HttpServletRequest req)
			throws IOException {
		boolean result = false;
		if (StringUtils.isEmpty(id)) {
			log.info("xxxxxxxx为空!!!");
			// 根据接口文档返回相应的json格式字符串值
			return false;
		} else if (StringUtils.isEmpty(sign)) {
			log.info("签名字符串为空!!!");

			return false;
		} else {
			StringBuilder builder = new StringBuilder();
			builder.append("id");
			builder.append(id);
			builder.append("key");
			builder.append("xxxxxxxx");

			String data = builder.toString();

			boolean checked = MD5Util.checkMD5Signature(data, sign);
			if (checked) {
				result = true;
			} else {
				log.info("数字签名失败！！！");

				return false;
			}
		}

		return result;
	}
}
